//
//  GPSStatisticViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Ding on 12/8/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "GPSStatisticViewController.h"

@interface GPSStatisticViewController ()

@end

@implementation GPSStatisticViewController
@synthesize sections=_sections;
@synthesize trackNameSection=_trackNameSection;
@synthesize startTimeSection=_startTimeSection;
@synthesize endTimeSection=_endTimeSection;
@synthesize travelTimeSection=_travelTimeSection;
@synthesize travelDistanceSection=_travelDistanceSection;
@synthesize maximumSpeedSection=_maximumSpeedSection;
@synthesize averageSpeedSection=_averageSpeedSection;
@synthesize stopTimesSection=_stopTimesSection;
@synthesize GPSLocationList=_GPSLocationList;
@synthesize GPSFileName=_GPSFileName;




- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil GPSLocationList:(NSMutableArray *)GPSLocationList GPSFileName:(NSString *)GPSFileName
{
    self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.GPSLocationList=GPSLocationList;
        self.GPSFileName=GPSFileName;
    }
    return self;
}

-(void)dealloc
{
    [_sections release];
    [_trackNameSection release];
    [_startTimeSection release];
    [_endTimeSection release];
    [_travelTimeSection release];
    [_travelDistanceSection release];
    [_averageSpeedSection release];
    [_stopTimesSection release];
    [_GPSLocationList release];
    [_GPSFileName release];
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if (!_trackNameSection) {
        _trackNameSection=[[TableSection alloc]init];
        
        _trackNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_trackNameSection.contents addObject:self.GPSFileName];
        
        _trackNameSection.header=@"GPS Track Name";
    }
    if (!_startTimeSection) {
        _startTimeSection=[[TableSection alloc] init];
         _startTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        if (self.GPSLocationList.count>0) {
            GPSEntity * startGPSLocation=[self.GPSLocationList objectAtIndex:0];
            NSDate *time=startGPSLocation.location.timestamp;
            
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *stringFromDate = [formatter stringFromDate:time];
            [_startTimeSection.contents addObject:stringFromDate];
            
        }else
        {
            [_startTimeSection.contents addObject:@""];
        }
        _startTimeSection.header=@"Start Time";
    
    }
    if (!_endTimeSection) {
        _endTimeSection=[[TableSection alloc] init];
        _endTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        if (self.GPSLocationList.count>0) {
            GPSEntity * endGPSLocation=[self.GPSLocationList lastObject];
            NSDate *time=endGPSLocation.location.timestamp;
            
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *stringFromDate = [formatter stringFromDate:time];
            [_endTimeSection.contents addObject:stringFromDate];
            
        }else
        {
            [_endTimeSection.contents addObject:@""];
        }
        _endTimeSection.header=@"End Time";
        
    }
    if (!_travelTimeSection) {
        _travelTimeSection=[[TableSection alloc] init];
        _travelTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        if (self.GPSLocationList.count>0) {
            GPSEntity *startGPSLocation=[self.GPSLocationList objectAtIndex:0];
            GPSEntity *endGPSLocation=[self.GPSLocationList lastObject];
            int timedifference=[endGPSLocation.location.timestamp timeIntervalSinceDate:startGPSLocation.location.timestamp];
            [_travelTimeSection.contents addObject:[NSString stringWithFormat:@"%d",timedifference]];
        }else
        {
            [_travelTimeSection.contents addObject:@"0"];
        }
        _travelTimeSection.header=@"Total Travel Time (second)";
    }
    if (!_travelDistanceSection) {
        _travelDistanceSection=[[TableSection alloc] init];
        _travelDistanceSection.contents=[[[NSMutableArray alloc] init] autorelease];
        double distance=0;
        self.maximumSpeed=0;
        if (self.GPSLocationList.count>0) {
            GPSEntity * GPSLocation=[self.GPSLocationList objectAtIndex:0];
            self.maximumSpeed=GPSLocation.location.speed;
        }
        for (int i=0; i<self.GPSLocationList.count-1; i++) {
            GPSEntity * GPSLocation=[self.GPSLocationList objectAtIndex:i];
            GPSEntity * nextGPSLocation=[self.GPSLocationList objectAtIndex:i+1];
            distance=distance+[nextGPSLocation.location distanceFromLocation:GPSLocation.location];
//            NSLog(@"Speed is: %f\n",nextGPSLocation.location.speed);
            if (self.maximumSpeed<=nextGPSLocation.location.speed) {
                self.maximumSpeed=nextGPSLocation.location.speed;
            }
        }
        [_travelDistanceSection.contents addObject:[NSString stringWithFormat:@"%.f", distance*3.28084]];
        _travelDistanceSection.header=@"Total Travel Distance (feet)";
        
    }
    if (!_averageSpeedSection) {
        _averageSpeedSection=[[TableSection alloc] init];
        _averageSpeedSection.contents=[[[NSMutableArray alloc] init] autorelease];
        double averageSpeed=0;
        if ([[_travelTimeSection.contents objectAtIndex:0] intValue]!=0) {
            averageSpeed=[[_travelDistanceSection.contents objectAtIndex:0] doubleValue]/(double)[[_travelTimeSection.contents objectAtIndex:0] intValue];
        }
        [_averageSpeedSection.contents addObject:[NSString stringWithFormat:@"%.f", averageSpeed*0.681818]];
        _averageSpeedSection.header=@"Average Speed (mile/hour)";
    }
    if (!_maximumSpeedSection) {
        _maximumSpeedSection=[[TableSection alloc] init];
        _maximumSpeedSection.contents=[[[NSMutableArray alloc] init] autorelease];
        
        [_maximumSpeedSection.contents addObject:[NSString stringWithFormat:@"%.f", self.maximumSpeed*2.23694]];
        _maximumSpeedSection.header=@"Maximum Speed (mile/hour)";
    }
    int count=0;
    if (!_stopTimesSection) {
        _stopTimesSection=[[TableSection alloc] init];
        _stopTimesSection.contents=[[[NSMutableArray alloc] init] autorelease];
        int stopTimes=0;
        for (int i=0; i<self.GPSLocationList.count; i++) {
            GPSEntity * GPSLocation=[self.GPSLocationList objectAtIndex:i];
//            GPSEntity * nextGPSLocation=[self.GPSLocationList objectAtIndex:i+1];
//            if (nextGPSLocation.location.speed*2.23694<5 &&nextGPSLocation.location.speed>0 && GPSLocation.location.speed*2.23694>=5) {
//                stopTimes=stopTimes+1;
//            }
            NSLog(@"Speed is: %f\n",GPSLocation.location.speed*2.23694);
            if (GPSLocation.location.speed*2.23694<5 &&GPSLocation.location.speed>=0)
            {
                if (count<10) {
                    count=count+1;
                    
                }
                
            }else
            {
                if (count>=10) {
                    stopTimes=stopTimes+1;
                    
                }
                count=0;
            }
            
        }
        [_stopTimesSection.contents addObject:[NSString stringWithFormat:@"%d", stopTimes]];
        _stopTimesSection.header=@"Stop Times";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        //        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.trackNameSection];
        [_sections addObject:self.startTimeSection];
        [_sections addObject:self.endTimeSection];
        [_sections addObject:self.travelTimeSection];
        [_sections addObject:self.travelDistanceSection];
        [_sections addObject:self.averageSpeedSection];
        [_sections addObject:self.maximumSpeedSection];
        [_sections addObject:self.stopTimesSection];
        //        [_sections addObject:self.linkButtonSection];
    }
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    UIBarButtonItem *configButtonItem= [[[ UIBarButtonItem alloc ] initWithTitle: @"Config" style: UIBarButtonItemStyleBordered target: self action: @selector( goToConfig:) ] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,configButtonItem,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.sections=nil;
    self.trackNameSection=nil;
    self.endTimeSection=nil;
    self.startTimeSection=nil;
    self.travelTimeSection=nil;
    self.travelDistanceSection=nil;
    self.averageSpeedSection=nil;
    self.stopTimesSection=nil;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;
    cell.textLabel.text=sectionContentString;
    
    // Configure the cell...
    
    return cell;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    
//    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
//    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
//    headerView.backgroundColor = [UIColor clearColor];
//    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
//    aLabel.text =[[self.sections objectAtIndex:section] header] ;
//    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
//    aLabel.textAlignment = UITextAlignmentLeft;
//    aLabel.backgroundColor = [UIColor clearColor];
//    aLabel.textColor=[UIColor darkGrayColor];
//    
//    
//    [headerView addSubview:aLabel];
//    return headerView;
//}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    return [[self.sections objectAtIndex:section] header];
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}



- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void) goToConfig:(id)sender
{
    GPSStatisticsConfigViewViewController *configCongroller=[[[GPSStatisticsConfigViewViewController alloc] initWithNibName:@"GPSStatisticsConfigViewViewController" bundle:nil] autorelease];
    [configCongroller setTitle:@"Statistics Config"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:configCongroller animated:YES];
}


@end
